using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using Servlets.Utils;

namespace Servlets
{
	public class Config
	{		
		public int SessionLengthInDays { 
			get {
				return int.Parse(map.GetOrDefault("sessionLengthInDays", "365"));
			}
		}
		public string ServletFolder {
			get {
				return map.GetOrDefault("servletFolder", "controllers");
			}
		}	
		public string ViewFolder {
			get {
				return map.GetOrDefault("viewFolder", "views");
			}
		}
		public string StaticRoot {
			get {
				return map.GetOrDefault("staticRoot", "staticroot");
			}
		}
		public bool ProtectViews {
			get {
				return bool.Parse(map.GetOrDefault("protectViews", "True"));
			}
		}
		
		
		private Dictionary<string, string> map = new Dictionary<string, string>();
		
		public Config(string path)
		{
			string[] lines = File.ReadAllLines(path);
			InitializeConfig(lines);
		}
		
		private void InitializeConfig(string[] lines) {
			foreach(string line in lines) {
				int index = line.IndexOf('#');
				if(index < 0) {
					index = line.Length;
				}
				string l = line.Substring(0, index).Trim();
				if(String.IsNullOrEmpty(l)) {
					continue;
				}
				
				string[] split = l.Split(new char[]{'='}, 2);
				if(split.Length < 1) {
					throw new InvalidDataException("Invalid line in the config.xml file");
				}
				
				string key = split[0].Trim();
				string val = split[1].Trim();
				map[key] = val;
				
				Log.WriteLine("[INFO] Property: " + key + " = " + val);
			}
		}
	}
}

